/*
 *  skeleton.cc
 *  wonderland-project
 *
 *  Created by Ben Nolan on 20/10/08.
 *  Copyright 2008 Nolan Consulting Limited. All rights reserved.
 *
 */

#include "skeleton.h"

#include <v8.h>
#include <Ogre.h>
#include "vector.h"
#include "quaternion.h"
#include "v8defines.h"
#include "scripting_context.h"
#include "bone.h"

namespace JSSkeleton{
  
  v8::Handle<v8::ObjectTemplate> instance_template;
  v8::Handle<v8::FunctionTemplate> function_template;
  v8::Persistent<v8::Context> context_;

  V8_GETTER(Skeleton,name){
    return v8::String::New(V8INTERNAL(Ogre::SkeletonInstance*)->getName().c_str());
  }
  
  V8_GETTER(Skeleton,bones){
    Ogre::SkeletonInstance *skel = V8INTERNAL(Ogre::SkeletonInstance*);
    
    int children = skel->getNumBones();
    v8::Handle<v8::Array> result_array = v8::Array::New(children); 

    for(int i=0;i<children;i++){
      result_array->Set(v8::Number::New(i), JSBone::New(
        skel->getBone(i)
      ));
    }
    
    return result_array;
  }
  
  V8CALLBACK(Skeleton,getBone){
    if(args.Length()!=1)
      return ThrowException(v8::String::New("Invalid argument"));

    v8::String::Utf8Value name(args[0]);
    
    if(!V8INTERNAL(Ogre::SkeletonInstance*)->hasBone(*name)){
      return v8::Null();
    }

    return JSBone::New(V8INTERNAL(Ogre::SkeletonInstance*)->getBone(*name));
  }

  /* Construct a new node - doesnt actually allocate the node, use world.createNode for that */
  V8CALLBACK(Skeleton,create){
    v8::Persistent<v8::Object> self = v8::Persistent<v8::Object>::New(args.Holder());
    return self;
  }

  /* Sets internal fields with our idiom of storing the class name in the second field */
  void setInternalFields(v8::Persistent<v8::Object> p, Ogre::SkeletonInstance *skel){
    p->SetInternalField(0, v8::External::New(skel));
    p->SetInternalField(1, v8::String::New("Skeleton"));
  }

  /* Only called from c++ */
  v8::Handle<v8::Value> New(Ogre::SkeletonInstance *skel){
    context_->Enter();

    v8::Persistent<v8::Object> instance = v8::Persistent<v8::Object>::New(function_template->GetFunction()->NewInstance());
    setInternalFields(instance, skel);
    return instance;
  }

  void Initialize(Wonderland::ScriptingContext *sc){
    context_ = sc->getContext();

    // Function Template
    function_template = v8::FunctionTemplate::New(Skeleton_create);
    function_template->SetClassName(v8::String::New("Skeleton"));

    // Instance template
    instance_template = function_template->InstanceTemplate();
    instance_template->SetInternalFieldCount(2);

    #define V8REGISTER(function) instance_template->Set(#function, v8::FunctionTemplate::New(Skeleton_ ## function));
    
    instance_template->SetAccessor(v8::String::New("name"), Skeleton_getname);
    instance_template->SetAccessor(v8::String::New("bones"), Skeleton_getbones);

    V8REGISTER(getBone);
  }

}

